<?php

/**
 * @Author:      zwh
 * @DateTime:    时间
 * @Description: 用于退货
 */
class ScsReturnOrderController extends BaseController
{
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-1 09:38:57
     * @Description: 用于显示退货单详情
     */
    public function returnOrderShow(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $orders=Orders::leftJoin('users','users.id','=','orders.user_id')
                ->where('order_id',$ro->order_id)
                ->select('orders.order_id','orders.pay_time','orders.name','orders.phone','orders.tittle',
                    'orders.car_brand_id','orders.car_brand_name','orders.car_series_id','orders.car_series_name',
                    'orders.car_model_id','orders.car_model_name','orders.payable_amount','orders.car_no','users.type',
                    'users.real_name as company_name')
                ->first();
            $opr=OrderPayRecord::where('order_id',$ro->order_id)->where('status',1)->select('id','pay_type','amount')->get();
            $ror=ReturnOrderRecord::where('return_order_id',Input::get('return_order_id'))->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order"=>$orders,"return_order"=>$ro,"order_pay_record"=>$opr,'return_order_record'=>$ror));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "returnOrderShow", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-27 11:23:55
     * @Description: 用于显示退货单列表
     */
    public function returnOrderList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);
    
            $sql="select  * from  (
				select id,return_order.order_id,reason,return_order.note,return_order.amount,created_by,created_name,approver,approver_name,return_order.status,return_order.created_at,return_order.updated_at,implement_time,return_order.verify_time,return_order.verify_status,1 type
				from return_order left join orders on orders.order_id=return_order.order_id  where return_order.status in(0,1) and orders.shop_id =".$sc_user->shop_id."
				union all
				select id,return_carwash_order.order_id,reason,return_carwash_order.note,return_carwash_order.amount,created_by,created_name,approver,approver_name,return_carwash_order.status,return_carwash_order.created_at,return_carwash_order.updated_at,implement_time,'' verify_time,'' verify_status,2 type
				from return_carwash_order left join car_wash_order on car_wash_order.order_id=return_carwash_order.order_id   where return_carwash_order.status in(0,1) and car_wash_order.shop_id=".$sc_user->shop_id."
                union all
                select id,rsco.order_id,reason,rsco.note,rsco.amount,created_by,created_name,approver,approver_name,rsco.status,rsco.created_at,rsco.updated_at,implement_time,'' verify_time,'' verify_status,3 type
                from return_service_card_order rsco left join service_card_order on service_card_order.order_id=rsco.order_id   where rsco.status in(0,1) and service_card_order.shop_id=".$sc_user->shop_id."

			) as temp ";
            $filt=" where 1=1 ";
            if(Input::get("order_id")!=""){
                $filt.=" and order_id like '%".Input::get("order_id")."%' or id like '%".Input::get("order_id")."%'";
            }
            if(Input::get("status")!=""){
                $filt.=" and status =".Input::get("status");
            }
            $sql=$sql.$filt;
            $limitsql= ' limit '.$page_size*($page-1).','.$page_size;
            $count=DB::select("select count(1) count from( ".$sql.") as count");
            $orders=DB::select($sql." order by created_at desc ".$limitsql);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count[0]->count,"orders"=>$orders));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "search_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-27 13:53:28
     * @Description: 创建退货订单
     */
    public function createReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "order_id"=>'required',
                "reason"=>'required',
                "note"=>'max:140',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(in_array($orders->status,array(1017,1117,1217,1417,1018))){
                if($orders->status==1117){
                    $response = Lang::get("scs_error.order_return_error_40056");
                    break;
                }
                if($orders->pay_type==10){
                    $response = Lang::get("scs_error.order_return_error_40057");
                    break;
                }
            }else{
                $response = Lang::get("scs_error.order_return_error_40053");
                break;
            }
            $returnOrder=ReturnOrder::whereIn('status',array(0,1))->where('order_id',Input::get('order_id'))->get();
            if(sizeof($returnOrder)>0){
                $response = Lang::get("scs_error.order_return_error_40043");
                break;
            }
            $ro = new ReturnOrder();
            $return_order_id = Common::createOrderId();
            $ro->id = $return_order_id;
            $ro->order_id = Input::get('order_id');
            $ro->reason =Input::get('reason');
            $ro->note = Input::get('note')?Input::get('note'):'';
            $ro->amount = 0;
            $ro->created_by = $sc_user->id;
            $ro->created_name = $sc_user->real_name;
            $ro->status = 0;
            $ro->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("return_order_id"=>$return_order_id));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "createReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-27 13:53:28
     * @Description: 退配件与工时列表
     */
    public function returnParts(){
        
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "order_id"=>'required',
                'return_order_id'=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $orders=Orders::find(Input::get('order_id'));
            if(is_null($orders)){
                $response = Lang::get("scs_error.order_notexiet_40000");
                break;
            }
            if($orders->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            if(!in_array($orders->status,Orders::$complete)){
                $response = Lang::get("scs_error.order_status_error_40027");
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            if(Input::get('order_id')!=$ro->order_id){
                $response = Lang::get("scs_error.order_note_shop_error_40003");
                break;
            }
            
            $items=ReturnOrder::getItemsByOrderId(Input::get('order_id'));
            $hours=ReturnOrder::getHoursByOrderId(Input::get('order_id'));
            $product=ReturnOrder::getProductByOrderId(Input::get('order_id'));            
            $roi=ReturnOrderItem::getByOrderId(Input::get('return_order_id'));
            
            /** 充减明细**/
            $return_money = [];
            $return_order_record  = ReturnOrderRecord::where('return_order_id',Input::get('return_order_id'))
                                    ->where('pay_type',8) 
                                    ->get()->toArray();
            
            if(!empty($return_order_record)){
                foreach($return_order_record as $value) { //一个退款对应多个退款记录
                    $acount_user_recharge_spendre_record = AcountUserRechargeSpendRe::where('status',1)->where("type",1)->where("buss_id",$value['id'])->get()->toArray();
                    if(!empty($acount_user_recharge_spendre_record)) {
                        foreach($acount_user_recharge_spendre_record as $b_values){  //一个退款记录对应多个消费退款充值记录
                            $array = AcountUserRecharge::RechargeInfo($b_values['aurr_id']); //根据充值记录，查找对应的门店名称和账户标虚
                            $key = $array['shop_id'].'_'.$array['acount_type'];
                            if(isset($return_money[$key])){
                                $return_money[$key]['amount'] += round(bcdiv($b_values['amount'],100,6),2);
                            } else {
                                $return_money[$key] = $array;
                                $return_money[$key]['amount'] = round(bcdiv($b_values['amount'],100,6),2);
                            }
                        }
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("items"=>$items['item1'],"item"=>$items['item2'],'hours'=>$hours,'return_order_item'=>$roi,'product'=>$product,'amount'=>$ro->amount,'return_money'=>  array_values($return_money)));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "returnParts", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-27 16:12:40
     * @Description: 添加 配件退库或退金额项
     */
    public function addReturnOrderItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'type' => 'required|in:0,1,2,3',
                'return_order_id' => 'required',//退货单
                'order_product_item_id' => 'numeric',
                'number' => 'min:0|numeric',
                'return_amount' => 'min:0|numeric'
             )
        );
        
        $return_amount=Input::get('return_amount',0)*100;
        $type=Input::get('type');
        $opii=Input::get('order_product_item_id');
        $return_order_id=Input::get('return_order_id');
        $product_type=Input::get('product_type');
        $num=Input::get('number',0);
        
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            DB::beginTransaction();
            $ro=ReturnOrder::find($return_order_id);
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }          
            
            $orders=Orders::find($ro->order_id);
            $ori0=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',0)->get();//退配件
            $ori1=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',1)->get();//退配件金额
            $ori2=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',2)->get();//退工时
            $ori3=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',3)->get();//均摊
            $ori4=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',4)->get();//推整包
            
            
            switch ($product_type) {
                case 'enterprise':
                    $item=OrderProductEsItem::find($opii);
                    if($item){
                        $opep=OrderProductEsPackage::find($item->order_product_package_id);
                        $op=OrderProduct::find($opep->order_product_id);
                    }
                    break;
                case 'activity':
                    $item=OrderProductAcItem::find($opii);
                    if($item){
                        $opacp=OrderProductAcPackage::find($item->order_product_package_id);
                        $op=OrderProduct::find($opacp->order_product_id);
                    }
                    break;
                case 'promotion':
                    $item=OrderProductItem::find($opii);                    
                    break;
                case 'base':
                    $item=OrderProductBaseItem::find($opii);
                    if($item){
                        $op=OrderProduct::find($item->order_product_package_id);
                    }
                    break;
                case 'non_standard':
                    $item=OrderProductNonStandard::find($opii);
                    if($item){
                        $op=OrderProduct::find($item->order_product_id);
                    }
                    break;
                case 'service_card':
                    $item=OrderProductScItem::find($opii);
                    if($item){
                        $op=OrderProduct::find($item->order_product_id);
                    }
                    break;
            }
            if(isset($op)){
                $sum=ReturnOrderItem::where('return_order_id',$return_order_id)->where('order_product_id',$op->id)->where('type',4)->whereIn('status',array(0,1))->first();
                if($sum){//如果该订单产品包退款
                    $response = Lang::get("scs_error.order_return_error_400134");
                    break;
                }
            }   
            
            
            if($type==0){//退配件 (退库存)
                //出库成功判断 为了防止假单结算退货
                if(!Orders::isOut($ro->order_id,Input::get('order_product_item_id'),$product_type)){
                    $response = Lang::get("scs_error.order_return_error_40055");
                    break;
                }
                if(sizeof($ori1)>0 || sizeof($ori3)>0){//退配件的话 只能都是退配件
                    $response = Lang::get("scs_error.order_return_error_40044");
                    break;
                }
                $number=ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->where('order_product_item_id',Input::get('order_product_item_id'))->where("product_type",$product_type)->whereIn('status',array(0,1))->sum('number');
                if(($number+$num)>$item->num){
                    $response = Lang::get("scs_error.order_return_error_40045");
                    break;
                }
                $return_amount=$item->counter_amount*$num;
                $ori=new ReturnOrderItem();
                $ori->return_order_id=$return_order_id;
                $ori->type=$type;
                $ori->order_product_item_id=$opii;
                $ori->product_type=$product_type;
                $ori->number=$num;
                $ori->amount=$item->counter_amount;
                $ori->return_amount=$return_amount;
                $ori->order_product_id=isset($op)?$op->id:0;
                $ori->status=0;
                $ori->save();
                $temp_return_amount=ceil($return_amount/100)*100;
                if($return_amount!=$temp_return_amount){//如果不相等说明 是小数需要工时补位
                    $hour=ReturnOrder::getHoursByOrderId($ro->order_id);       
                    $temp_buwei_amount=$temp_return_amount-$return_amount; //需要补位的金额   
                    foreach ($hour as $h) {//循环工时 去补位
                        $allow_return_amount=$h->counter_amount;//配件销售额                        
                        $ra_amount=ReturnOrderItem::where('return_order_id',$return_order_id)->where('order_product_item_id',$h->id)->where("product_type",$h->product_type)->whereIn('status',array(0,1))->sum('return_amount');
                        $can_return=0;
                        if(bccomp(($ra_amount+$temp_buwei_amount),$allow_return_amount,0)>0){//如果说要补位的数据大于 该工时所剩的 可推
                            $can_return=$allow_return_amount-$ra_amount;//推完改项的工时
                            $temp_buwei_amount=$temp_buwei_amount-$can_return;//是算出剩余需要继续补位的
                        }else{//如果 改工时能满足所有的 补位需求 
                            $can_return=$temp_buwei_amount;//
                            $temp_buwei_amount=0;
                        }
                        $sori=new ReturnOrderItem();
                        $sori->return_order_id=$return_order_id;
                        $sori->type=2;
                        $sori->order_product_item_id=$h->id;
                        $sori->product_type=$h->product_type;
                        $sori->number=0;
                        $sori->amount=0;
                        $sori->return_amount=$can_return;
                        $sori->order_product_id=$h->order_product_id;
                        $sori->status=0;
                        $sori->can_delete=0;
                        $sori->save();
                        $ora=new OrderReturnAutoplacement();
                        $ora->supply_return_order_item_id=$ori->id;
                        $ora->hour_return_order_item_id=$sori->id;
                        $ora->save();
                        if($temp_buwei_amount==0){//补位完毕 跳出循环
                            break;
                        }
                    }  
                    if($temp_buwei_amount!=0){//说明补位未完成
                        $response = Lang::get("scs_error.order_return_error_400000");
                        DB::rollback();
                        break;
                    }
                    $return_amount=$temp_return_amount;
                }
            }elseif($type==1){//退配件金额
                if(sizeof($ori0)>0 || sizeof($ori3)>0){
                    $response = Lang::get("scs_error.order_return_error_40044");
                    break;
                }
                
                $cost=ReturnOrderItem::getCost($opii,$product_type,$ro->order_id);
                $sale_cost=$item->counter_amount*$item->num;//配件销售额
                $allow_return_amount=sprintf("%.2f",$sale_cost-$cost);//配件毛利
                
                if($return_amount > $allow_return_amount){
                    $response = Lang::get("scs_error.order_return_error_40047");
                    break;
                }
                
                $ra=ReturnOrderItem::where('return_order_id',$return_order_id)->where('order_product_item_id',$opii)->whereIn('status',array(0,1))->sum('return_amount');
                if(($ra+$return_amount)>$allow_return_amount){
                    $response = Lang::get("scs_error.order_return_error_40047");
                    break;
                }
                $ori=new ReturnOrderItem();
                $ori->return_order_id=$return_order_id;
                $ori->type=$type;
                $ori->order_product_item_id=$opii;
                $ori->product_type=$product_type;
                $ori->number=0;
                $ori->amount=0;
                $ori->return_amount=$return_amount;
                $ori->order_product_id=isset($op)?$op->id:0;
                $ori->status=0;
                $ori->save();
                $temp_return_amount=ceil($return_amount/100)*100;
                if($return_amount!=$temp_return_amount){//如果不相等说明 是小数需要工时补位
                    $hour=ReturnOrder::getHoursByOrderId($ro->order_id);       
                    $temp_buwei_amount=$temp_return_amount-$return_amount; //需要补位的金额   
                    foreach ($hour as $h) {//循环工时 去补位
                        $allow_return_amount=$h->counter_amount;//配件销售额                        
                        $ra_amount=ReturnOrderItem::where('return_order_id',$return_order_id)->where('order_product_item_id',$h->id)->where("product_type",$h->product_type)->whereIn('status',array(0,1))->sum('return_amount');
                        $can_return=0;
                        if(bccomp(($ra_amount+$temp_buwei_amount),$allow_return_amount,0)>0){//如果说要补位的数据大于 该工时所剩的 可推
                            $can_return=$allow_return_amount-$ra_amount;//推完改项的工时
                            $temp_buwei_amount=$temp_buwei_amount-$can_return;//是算出剩余需要继续补位的
                        }else{//如果 改工时能满足所有的 补位需求 
                            $can_return=$temp_buwei_amount;//
                            $temp_buwei_amount=0;
                        }
                        $sori=new ReturnOrderItem();
                        $sori->return_order_id=$return_order_id;
                        $sori->type=2;
                        $sori->order_product_item_id=$h->id;
                        $sori->product_type=$h->product_type;
                        $sori->number=0;
                        $sori->amount=0;
                        $sori->return_amount=$can_return;
                        $sori->order_product_id=$h->order_product_id;
                        $sori->status=0;
                        $sori->can_delete=0;
                        $sori->save();
                        $ora=new OrderReturnAutoplacement();
                        $ora->supply_return_order_item_id=$ori->id;
                        $ora->hour_return_order_item_id=$sori->id;
                        $ora->save();
                        if($temp_buwei_amount==0){//补位完毕 跳出循环
                            break;
                        }
                    }  
                    if($temp_buwei_amount!=0){//说明补位未完成
                        $response = Lang::get("scs_error.order_return_error_400000");
                        DB::rollback();
                        break;
                    }
                    $return_amount=$temp_return_amount;
                }
            }elseif($type==2){//工时退款
                if(sizeof($ori3)>0){
                    $response = Lang::get("scs_error.order_return_error_40044");
                    break;
                }
                $allow_return_amount=$item->counter_amount;//配件销售额
                // if(bccomp($return_amount,$allow_return_amount,0)>0){
                // // if($return_amount > $allow_return_amount){
                //     $response = Lang::get("scs_error.order_return_error_40047");
                //     break;
                // }
                
                $ra=ReturnOrderItem::where('return_order_id',$return_order_id)->where('order_product_item_id',$opii)->where("product_type",$product_type)->whereIn('status',array(0,1))->sum('return_amount');
                if(bccomp(($ra+$return_amount),$allow_return_amount,0)>0){
                // if(($ra+$return_amount)>$allow_return_amount){
                    $response = Lang::get("scs_error.order_return_error_40047");
                    break;
                }
                $ori=new ReturnOrderItem();
                $ori->return_order_id=$return_order_id;
                $ori->type=$type;
                $ori->order_product_item_id=$opii;
                $ori->product_type=$product_type;
                $ori->number=0;
                $ori->amount=0;
                $ori->return_amount=$return_amount;
                $ori->order_product_id=isset($op)?$op->id:0;
                $ori->status=0;
                $ori->save();
            }elseif($type==3){//均摊退款金额
                if(sizeof($ori0)>0 || sizeof($ori1)>0 || sizeof($ori2)>0|| sizeof($ori4)>0){
                    $response = Lang::get("scs_error.order_return_error_40044");
                    break;
                }
                
                $allow_return_amount=$orders->payable_amount;//配件销售额
                if($return_amount > $allow_return_amount){
                    $response = Lang::get("scs_error.order_return_error_40047");
                    break;
                }
                $all=ReturnOrder::getAllByOrderId($ro->order_id);
                $discount=$return_amount/$orders->payable_amount;
                
                $ori=new ReturnOrderItem();
                $ori->return_order_id=$return_order_id;
                $ori->type=$type;
                $ori->order_product_item_id=0;
                $ori->product_type='enterprise';
                $ori->number=0;
                $ori->amount=0;
                $ori->status=0;
                $ori->return_amount=$return_amount;
                $ori->save();
                
                foreach($all as $_item){
                    $ori=new ReturnOrderItem();
                    $ori->return_order_id=$return_order_id;
                    $ori->type=$type;
                    $ori->order_product_item_id=$_item->id;
                    $ori->product_type=$_item->product_type;
                    $ori->number=0;
                    $ori->amount=0;
                    $ori->status=3;//此状态暂无意义只为了不显示耗材均摊项
                    
                    switch ($_item->product_type) {
                        case 'enterprise':
                            if($_item->type==1){
                                $ori->return_amount=round($_item->num*$_item->counter_amount*$discount);
                            }else{
                                $ori->return_amount=round($_item->counter_amount*$discount);
                            }
                            break;
                        case 'activity':
                            if($_item->type==1){
                                $ori->return_amount=round($_item->num*$_item->counter_amount*$discount);
                            }else{
                                $ori->return_amount=round($_item->counter_amount*$discount);
                            }
                            break;
                        case 'promotion':
                            if($_item->type==1){
                                $ori->return_amount=round($_item->num*$_item->counter_amount*$discount);
                            }else{
                                $ori->return_amount=round($_item->counter_amount*$discount);
                            }
                            break;
                        case 'base':
                            if($_item->type==1){
                                $ori->return_amount=round($_item->num*$_item->counter_amount*$discount);
                            }else{
                                $ori->return_amount=round($_item->counter_amount*$discount);
                            }
                            break;
                        case 'non_standard':
                            if($_item->service_type==1){
                                $ori->return_amount=round($_item->num*$_item->counter_amount*$discount);
                            }else{
                                $ori->return_amount=round($_item->counter_amount*$discount);
                            }
                            break;
                    }
                    $ori->save();
                }
            }
            $ro->amount+=$return_amount;
            $ro->save();
            DB::commit();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addReturnOrderItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-08-04 15:37:58
     * @Description: 用于退货单添加整个产品包的方法
     */
    public function addReturnProduct(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'return_order_id' => 'required',//退货单
                'order_product_id' => 'numeric',
             )
        );        
        $order_product_id=Input::get('order_product_id');
        $return_order_id=Input::get('return_order_id');
        
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $ro=ReturnOrder::find($return_order_id);
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $ori3=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',3)->get();//均摊
            if(sizeof($ori3)>0){
                $response = Lang::get("scs_error.order_return_error_40044");
                break;
            }
            $op=OrderProduct::find($order_product_id);
            $sum=ReturnOrderItem::where('return_order_id',$ro->id)->where('order_product_id',$op->id)->where('type',4)->whereIn('status',array(0,1))->first();
            if($sum){//如果该订单产品包退款
                $response = Lang::get("scs_error.order_return_error_400135");
                break;
            }
            switch ($op->product_type) {
                case 'enterprise':
                    $opp_ids=OrderProductEsPackage::where("order_product_id",$op->id)->select('id')->get()->toArray();
                    $opp_ids = array_column($opp_ids, 'id');
                    $opei=OrderProductEsItem::whereIn('order_product_package_id',$opp_ids)->get();
                    foreach ($opei as $key=>$_item) { //查看是否 该包中已经被添加过 退货
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"enterprise")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
                case 'activity':
                    $opp_ids=OrderProductAcPackage::where("order_product_id",$op->id)->select('id')->get()->toArray();
                    $opp_ids = array_column($opp_ids, 'id');
                    $opaci=OrderProductAcItem::whereIn('order_product_package_id',$opp_ids)->get();
                    foreach ($opaci as $key=>$_item) {
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"activity")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
                case 'promotion':
                    $opp_ids=OrderProductPackage::where("order_product_id",$op->id)->select('id')->get()->toArray();
                    $opp_ids = array_column($opp_ids, 'id');
                    $items=OrderProductItem::where('type',1)->whereIn('order_product_package_id',$opp_ids)->get()->toArray();
                    foreach ($items as $key=>$_item) {
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"promotion")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
                case 'base':
                    $opp=OrderProductBaseItem::where("order_product_package_id",$op->id)
                    ->get();
                    foreach ($opp as $key=>$_item) {
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"base")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
                case 'non_standard':
                    $opn=OrderProductNonStandard::where("order_product_id",$op->id)
                    ->where('order_product_non_standard.status',1)
                    ->get();
                    foreach ($opn as $key=>$_item) {
                        //判断产品项是非标还是标准配件
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"non_standard")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
                case 'service_card':
                    $opp=OrderProductScItem::where("order_product_id",$op->id)
                    ->get();
                    foreach ($opp as $key=>$_item) {
                        $f=ReturnOrderItem::where('order_product_item_id',$_item->id)->where('product_type',"service_card")->where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->first();
                        if($f){
                            $response = Lang::get("scs_error.order_return_error_400136");
                            break 3;
                        }
                    }
                    break;
            }
            $ori=new ReturnOrderItem();
            $ori->return_order_id=$return_order_id;
            $ori->type=4;
            $ori->order_product_item_id=0;
            $ori->product_type=$op->product_type;
            $ori->number=1;
            $ori->amount=$op->counter_amount;
            $ori->status=0;
            $ori->return_amount=$op->counter_amount;
            $ori->order_product_id=$op->id;
            $ori->save();            
            
            $ro->amount+=$op->counter_amount;
            $ro->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "addReturnOrderItem", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-29 17:32:24
     * @Description: 取消单个退货项
     */
    public function cancelReturnOrderItem(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_item_id"=>'required',
                'return_order_id'=>'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            $roi=ReturnOrderItem::find(Input::get('return_order_item_id'));
            if(is_null($roi) || $roi->status==2){
                $response = Lang::get("scs_error.order_return_error_40048");
                break;
            }
            if($roi->can_delete!=1){
                $response = Lang::get("scs_error.order_return_error_400001");
                break;
            }
            $return_order_id=Input::get('return_order_id');
            if($roi->return_order_id!=$return_order_id){
                $response = Lang::get("scs_error.order_return_error_40049");
                break;
            }
            $roi->status=2;
            $roi->save();
            $temp_amount=0;
            $temp_amount+=$roi->return_amount;
            if($roi->type==3){
                ReturnOrderItem::where('return_order_id',$return_order_id)->where('type',3)->where('order_product_item_id','!=',0)->delete();
            }
            $ora=OrderReturnAutoplacement::where("supply_return_order_item_id",$roi->id)->get();
            foreach ($ora as $_ora) {
                $tro=ReturnOrderItem::find($_ora->hour_return_order_item_id);
                $tro->status=2;
                $tro->save();
                $temp_amount+=$tro->return_amount;
            }
            $ro->amount-=$temp_amount;
            $ro->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelReturn", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-29 17:32:24
     * @Description: 取消退货单
     */
    public function cancelReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $or=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($or) || $or->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->update(array('status'=>2));
            
            $or->status=2;
            $or->save();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "cancelReturnOrder", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 

    /**
     * @Author   lyt                      <ahlyt@anhuibj.com>
     * @DateTime 2018-08-29T12:35:11+0800
     * @return   [type]                   [快捷整单的]
     */
    public function allReturn(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $orders=Orders::find($ro->order_id);
            // $ori3=ReturnOrderItem::where('return_order_id',$return_order_id)->whereIn('status',array(0,1))->where('type',3)->get();//均摊
            // if(sizeof($ori3)>0){
            //     $response = Lang::get("scs_error.order_return_error_40044");
            //     break;
            // }
            ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->update(array('status'=>2));//清除现有的退款项 

            $order_product=OrderProduct::where("order_id",$ro->order_id)->where("status",1)->get();
            foreach ($order_product as $op) {
                $ori=new ReturnOrderItem();
                $ori->return_order_id=$ro->id;
                $ori->type=4;
                $ori->order_product_item_id=0;
                $ori->product_type=$op->product_type;
                $ori->number=1;
                $ori->amount=$op->counter_amount;
                $ori->status=0;
                $ori->return_amount=$op->counter_amount;
                $ori->order_product_id=$op->id;
                $ori->save();  
            }
            $ro->amount=$orders->payable_amount;
            $ro->save();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "allReturn", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    } 
    
    
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-30 10:38:08
     * @Description: 授权信息
     */
    public function accredit(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_order_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            
            $order_id=$ro->order_id;
            $orders=Orders::find($order_id);
            $date=date('Y-m-d',time());
            $paytime=explode(' ',$orders->pay_time);
            if($paytime[0]==$date){
                $accredit_type=array(
                    //array("type"=>0),
                    array("type"=>1)
                    );
                $select_arr = [
                    //'id','real_name',
                    'id','real_name AS name',
                ];
                $me=SCUser::where('status',1)->where('shop_id',$sc_user->shop_id)->where('title',1)->select($select_arr)->get();
                //$result=array('accredit_type'=>$accredit_type,'shop_manager'=>$me);
                $result=array('accredit_type'=>$accredit_type,'approver'=>$me);
                
            }else{
                 $accredit_type=array(
                    array("type"=>1)
                    );
                 $temp_ca=CityAuthorization::where("city_id",$orders->city)->where("return",1)->where("status",1)->select("id","name")->get();
                 $result=array('accredit_type'=>$accredit_type,'approver'=>$temp_ca);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-7-30 16:17:58
     * @Description: 执行
     */
    public function implementReturnOrder(){
        $validator = Validator::make(Input::all(),
            array(
                'token'    => 'required',
                "return_type"=>'required',
                "return_order_id"=>'required',
                "type"=>'required',
                "code"=>'numeric',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $return_order_id    = Input::get('return_order_id');   //退货单id
            $type               = Input::get('type');   //授权类型 (0:账号授权;1:动态授权;)
            $id                 = Input::get('id');     //用户id (店长id、城市经理人id)
            $code               = Input::get('code', '');   //短信验证码
            if($type == 1){
                $phone              = '';   //接收短信的手机号
                $approver           = 0;
                $approver_name      = '';
                //获取订单支付时间信息
                $select_arr = [
                    'orders.pay_time', 
                ];
                $order_info = Orders::leftJoin('return_order', 'orders.order_id', '=', 'return_order.order_id')
                        ->where('return_order.id', $return_order_id)
                        ->select($select_arr)
                        ->first();
                if(!$order_info){
                    $response = Lang::get('scs_error.order_return_error_40046');
                    break;
                }

                $date = date('Y-m-d',time());
                $paytime = explode(' ',$order_info->pay_time);
                if($paytime[0] == $date){
                    //当日订单
                    $user_info = SCUser::find($id);
                    if($user_info){
                        $phone = $user_info->phone;
                        $approver_name = $user_info->real_name;
                    }
                }else{
                    //往日订单
                    $user_info = CityAuthorization::find($id);
                    if($user_info){
                        $phone = $user_info->phone;
                        $approver_name = $user_info->name;
                    }
                }
                
                //判断验证码是否存在
                $record = UserCheckCodeUpgrade::where('business_id', $return_order_id)
                        ->where('business_type', 'return_order')
                        ->where('phone', $phone)
                        ->first();
                if(is_null($record)){ //没有记录
                    $response = Lang::get("error.user_login_checkcode_null_1012");
                    break;
                }
                //校验是否超过时限
                if( time() > Common::datetime2Num($record->out_time_at) ){
                    $response = Lang::get("error.user_login_checkcode_timeout_1013");
                    break;
                }
        
                //校验验证码是否匹配
                if($record->check_code != $code){
                    $response = Lang::get("error.user_login_checkcode_error_1014");
                    break;
                }
            }else{
                //原先的 店长账号密码授权
                $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
                if(is_null($sc)){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
                $approver=$sc->id;
                $approver_name=$sc->real_name;
            }
            $count=ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->where('status',0)->count();
            if($count <= 0){
                $response = Lang::get("scs_error.order_return_error_40054");
                break;
            }
            $ro=ReturnOrder::find(Input::get('return_order_id'));
            if(is_null($ro) || $ro->status==2){
                $response = Lang::get("scs_error.order_return_error_40046");
                break;
            }
            $temp_return_amount=ceil($ro->amount/100)*100;
            if($temp_return_amount!=$ro->amount){//说明金额不对有小数
                $response = Lang::get("scs_error.order_return_error_400002");
                break;
            }
            $return_type=json_decode(Input::get('return_type'),1);
            $s=0;
            foreach($return_type as $_rt){
                $s+=$_rt["amount"];
            }
            $s=(int)bcmul($s,100);
            if($s != $ro->amount){
                $response = Lang::get("scs_error.order_return_error_40052");
                break;
            }
            
            $roi=ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->where('type',0)->where('status',0)->select('order_product_item_id','number','product_type')->get();
            $roi_array=array();
            foreach ($roi as $_roi) {
                $roi_array[]=$_roi;
            }
            $cancel_arr=array();
            $roi_four=ReturnOrderItem::where('return_order_id',Input::get('return_order_id'))->where('type',4)->where('status',0)->get();
            foreach ($roi_four as $_roi_four) {
                $_op=OrderProduct::find($_roi_four->order_product_id);                                  
                switch ($_op->product_type) {
                    case 'enterprise':
                        $opp_ids=OrderProductEsPackage::where("order_product_id",$_op->id)->select('id')->get()->toArray();
                        $opp_ids = array_column($opp_ids, 'id');
                        $opei=OrderProductEsItem::where('type',1)->whereIn('order_product_package_id',$opp_ids)->get();
                        foreach ($opei as $key=>$_item) {
                            $obj1 = new \stdClass();
                            $obj1->product_type='enterprise';
                            $obj1->order_product_item_id=$_item->id;
                            $obj1->number=$_item->num;
                            $roi_array[]=$obj1;
                        }
                        break;
                    case 'activity':
                        $opp_ids=OrderProductAcPackage::where("order_product_id",$_op->id)->select('id')->get()->toArray();
                        $opp_ids = array_column($opp_ids, 'id');
                        $opaci=OrderProductAcItem::where('type',1)->whereIn('order_product_package_id',$opp_ids)->get();
                        foreach ($opaci as $key=>$_item) {
                            $obj1 = new \stdClass();
                            $obj1->product_type='activity';
                            $obj1->order_product_item_id=$_item->id;
                            $obj1->number=$_item->num;
                            $roi_array[]=$obj1;
                        }
                        break;
                    case 'promotion':                           
                        break;
                    case 'base':
                        $opp=OrderProductBaseItem::where("order_product_package_id",$_op->id)
                        ->where('type',1)
                        ->get();
                        foreach ($opp as $key=>$_item) {
                            $obj1 = new \stdClass();
                            $obj1->product_type='base';
                            $obj1->order_product_item_id=$_item->id;
                            $obj1->number=$_item->num;
                            $roi_array[]=$obj1;
                        }
                        break;
                    case 'non_standard':
                        $opn=OrderProductNonStandard::where("order_product_id",$_op->id)
                        ->where('service_type',1)
                        ->where('order_product_non_standard.status',1)
                        ->get();
                        foreach ($opn as $key=>$_item) {
                            $obj1 = new \stdClass();
                            $obj1->product_type='non_standard';
                            $obj1->order_product_item_id=$_item->id;
                            $obj1->number=$_item->num;
                            $roi_array[]=$obj1;
                        }
                        break;
                    case 'service_card':
                        $opp=OrderProductScItem::where("order_product_id",$_op->id)
                        ->where('type',1)
                        ->get();
                        foreach ($opp as $key=>$_item) {
                            $obj1 = new \stdClass();
                            $obj1->product_type='service_card';
                            $obj1->order_product_item_id=$_item->id;
                            $obj1->number=$_item->num;
                            $roi_array[]=$obj1;
                        }
                        $cancel_arr[]=$_op->id;
                        break;
                }
                
            }
            $response=ReturnOrderItem::implement(Input::get('return_order_id'),$roi_array,$ro->order_id,$sc_user,$ro, $approver,$approver_name,$return_type,$cancel_arr);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-8-3 18:47:58
     * @Description: 发短信 (退货单执行前发送动态校验短信)
     * @param string $token     用户token
     * @param string $return_order_id  退货单id
     * @param int $id         用户id(店长id、城市经理人id)
     * @link http://api.anhui.com/v1/scs/order/sendMessage?token=8fb96daa6a2373b2d23fad8ecd58f293&return_order_id=15355924641212&id=155
     */
    public function sendMessage(){
        $validator = Validator::make(Input::all(),
            array(
                'token'  => 'required',
                'id' => 'required',
                'return_order_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result'=>array('order_id'=>Input::get('order_id')));
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            
            $return_order_id    = Input::get('return_order_id');    //退货单id
            $id                 = Input::get('id');                 //用户id(店长id、城市经理人id)
            $phone              = '';   //接收短信的手机号
            $area               = '';   //区号
            //获取订单支付时间信息
            $select_arr = [
                'orders.pay_time', 
            ];
            $order_info = Orders::leftJoin('return_order', 'orders.order_id', '=', 'return_order.order_id')
                    ->where('return_order.id', $return_order_id)
                    ->select($select_arr)
                    ->first();
            if(!$order_info){
                $response = Lang::get('scs_error.order_return_error_40046');
                break;
            }
            
            $date = date('Y-m-d',time());
            $paytime = explode(' ',$order_info->pay_time);
            if($paytime[0] == $date){
                //当日订单
                $user_info = SCUser::find($id);
                if($user_info){
                    $phone = $user_info->phone;
                }
            }else{
                //往日订单
                $user_info = CityAuthorization::find($id);
                if($user_info){
                    $phone = $user_info->phone;
                }
            }
            $time_out_default = Config::get("user.time_out_default");
            //检查手机号是否下发验证码
            $record = UserCheckCodeUpgrade::where('business_id', $return_order_id)
                    ->where('business_type', 'return_order')
                    ->where('phone', $phone)
                    ->first();
            if(!is_null($record)){ //有记录
                //判断是否超时
                if( time() < Common::datetime2Num($record->out_time_at) ){ //没有超过时限
                    try {
                        $sms_send_record_id = Sms::send_message($area, $phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$record->check_code);
                    } catch (Exception $e) {
                        Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                        $response = Lang::get("error.user_sms_check_code_send_error_1003");
                        break;
                    }
                    $response = array(
                        'code' => 0,
                        'msg' => 'ok',
                        'result' => array(
                            'out_time' => Common::datetime2Num($record->out_time_at) - time(),
                            //'check_code' => $record->check_code // todo 调试使用
                        ));
                    break;
                }else{ //超过限时
                    $record->delete();
                }
            }
            //超过时限和没有记录
            //生成验证码
            $check_code = Common::generateCode();
            //调用短信网关发送短信
            try {
                $sms_send_record_id = Sms::send_message($area, $phone,'您好：'.$sc_user->shop->name.'，申请退货业务，退货单：'.$return_order_id.'，您的授权码为'.$check_code);
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "sendMessage", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_sms_check_code_send_error_1003");
                break;
            }
            
            $record = new UserCheckCodeUpgrade;
            $record->business_type = 'return_order';
            $record->business_id = $return_order_id;
            $record->phone = $phone;
            $record->area = $area;
            $record->check_code = $check_code;
            $record->out_time_at = Common::num2DateTime(time() + $time_out_default);
            $record->send_id = $sms_send_record_id;           
            $record->save();
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'out_time' => $time_out_default,
                ));
            
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "accredit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}